﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.FieldReader;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.FormPlugIn.ZhuMuNiao
{
    [Description("zmn发货通知单编辑表单插件"), HotUpdate]
    public class zmnFH : AbstractBillPlugIn
    {
        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);
            var obj = this.Model.DataObject;
            DynamicObject cust = obj["CustomerID"] as DynamicObject;
            DynamicObject custJDZC = cust == null ? null : cust["F_zmn_jdfkzc"] as DynamicObject;
            string jdzcNumber = custJDZC == null ? "" : Convert.ToString(custJDZC["number"]);
            var fina = (obj["SAL_DELIVERYNOTICEFIN"] as DynamicObjectCollection)[0];
            decimal BillAllAmount = Convert.ToDecimal(fina["BillAllAmount"]);
            DynamicObjectCollection skmx = this.Model.DataObject["POSW_Cust_Entry100002"] as DynamicObjectCollection;
            // 创建新集合
            DynamicObjectCollection filteredCollection = new DynamicObjectCollection();

            // 使用 LINQ 筛选
            var filteredItems = skmx.Cast<DynamicObject>()
                                  .Where(item =>
                                  {
                                      string value = item["F_zmn_xsddh"] as string;
                                      return string.IsNullOrWhiteSpace(value);
                                  });

            // 逐个添加元素
            foreach (var item in filteredItems)
            {
                filteredCollection.Add(item);
            }
            int i = 1;
            foreach (var sk in filteredCollection)
            {
                string skdh = sk["F_POSW_Text_dvn"] == null ? "" : sk["F_POSW_Text_dvn"].ToString();
                decimal fhysje = Convert.ToDecimal(sk["FActRecAmount"]);
                decimal kyskje = Convert.ToDecimal(sk["F_zmn_syskje"]);
                if (fhysje > kyskje)
                {
                    e.Cancel = true;
                    this.View.ShowErrMessage($"收款单号：{skdh}，使用收款金额:{fhysje},比可用收款金额:{kyskje.ToString("G29")}大，不允许保存！");
                    return;
                }
                i++;
            }
            // 按 F_POSW_Text_dvn 字段分组并汇总 FActRecAmount
            var groupedResult = filteredCollection
                .Cast<DynamicObject>()  // 转换为可枚举的 DynamicObject
                .GroupBy(item => item["F_POSW_Text_dvn"]?.ToString())  // 按分组字段分组
                .Select(g => new
                {
                    GroupKey = g.Key,  // 分组字段值
                    TotalAmount = g.Sum(item =>
                        Convert.ToDecimal(item["FActRecAmount"] ?? 0m))  // 汇总金额
                })
                .ToList();  // 转换为列表
            foreach (var g in groupedResult)
            {
                string dh = g.GroupKey == null ? "" : g.GroupKey.Trim();
                decimal je = g.TotalAmount;
                decimal cyje = GetKysgje(dh);
                if (je > cyje)
                {
                    e.Cancel = true;
                    this.View.ShowErrMessage($"使用收款金额:{je.ToString("G29")},比收款单{dh}剩余收款金额:{cyje.ToString("G29")}大，不允许保存！");
                    return;
                }
            }

            var FActRecAmount = skmx.Select(s => Convert.ToDecimal(s["FActRecAmount"])).Sum(m => m);
            var F_POSW_KYQty2 = Convert.ToDecimal(obj["F_POSW_KYQty2"]);
            FActRecAmount = FActRecAmount + F_POSW_KYQty2;
            if (FActRecAmount < BillAllAmount)
            {
                this.Model.SetValue("FIsWorlk", 2);
            }
            else
            {
                this.Model.SetValue("FIsWorlk", 1);
            }
        }

        private decimal GetSKDCYJE(string dh)
        {
            throw new NotImplementedException();
        }

        public override void BeforeF7Select(BeforeF7SelectEventArgs e)
        {
            base.BeforeF7Select(e);
            if (e.FieldKey.ToUpperInvariant() == "F_POSW_TEXT_DVN")
            {
                ShowSKDLB(e.Row);
            }
        }
        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            if (e.Field.Key.Equals("F_POSW_Text_dvn"))
            {
                decimal kysgje = GetKysgje((string)e.NewValue);
                this.View.Model.SetValue("F_zmn_syskje", kysgje, e.Row);//可用收款金额
                //this.View.Model.SetValue("F_POSW_Amount_0jm", kysgje, e.Row);//使用收款金额
                //this.View.Model.SetValue("F_zmn_syskje", 0, e.Row);//剩余收款金额
            }
        }

        private decimal GetKysgje(string newValue)
        {
            string sql = string.Format(@"/*dialect*/ 
            select F_zmn_Ssyskje from T_AR_RECEIVEBILL where FBILLNO='{0}' ", newValue);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToDecimal(doc[0][0]);
            }
            return 0;
        }

        /// <summary>
        /// 返回收款单
        /// </summary>
        /// <param name="row"></param>
        private void ShowSKDLB(int row)
        {
            DynamicObject customer = this.Model.DataObject["CustomerID"] as DynamicObject;
            int customerId = customer == null ? 0 : Convert.ToInt32(customer["id"]);
            DynamicObjectCollection finec = this.Model.DataObject["SAL_DELIVERYNOTICEFIN"] as DynamicObjectCollection;
            DynamicObject curr = finec[0]["SettleCurrID"] as DynamicObject;
            int currId = curr == null ? 0 : Convert.ToInt32(curr["id"]);
            decimal allAmount = Convert.ToDecimal(finec[0]["BillAllAmount"]);
            DynamicObjectCollection skmx = this.Model.DataObject["POSW_Cust_Entry100002"] as DynamicObjectCollection;
            // 方法2：增强版（推荐 - 同时处理 null 和 DBNull）
            var ysk = skmx.Select(s => s["F_POSW_Text_dvn"])
                          .Where(value =>
                              value != null &&
                              value != DBNull.Value
                          );
            List<string> newList = new List<string>();
            foreach (var a in ysk)
            {
                string b = " and FBILLNO not in " + $"('{a}')";
                newList.Add(b);
            }
            string yskNos = string.Join("  ", newList);
            ListSelBillShowParameter list = new ListSelBillShowParameter();
            //list.ListFilterParameter.Filter = string.Format(" FPAYUNITTYPE='BD_Customer' AND FPAYUNIT = '{0}' AND FCURRENCYID='{1}' AND F_ZMN_SSYSKJE>0  {2} ", customerId, currId, yskNos);
            list.ListFilterParameter.Filter = string.Format(" FPAYUNITTYPE='BD_Customer' AND FPAYUNIT = '{0}' AND FCURRENCYID='{1}' AND F_ZMN_SSYSKJE>0   ", customerId, currId);
            list.FormId = "AR_RECEIVEBILL";
            list.MultiSelect = false;
            this.View.ShowForm(list, delegate (FormResult result)
            {
                ListSelectedRowCollection results = result.ReturnData as ListSelectedRowCollection;
                Dictionary<string, decimal> dic = new Dictionary<string, decimal>();
                if (null != results && results.Count > 0)
                {
                    foreach (ListSelectedRow item in results)
                    {
                        string BillNo = item.BillNo;
                        DynamicObjectDataRow datarows = item.DataRow as DynamicObjectDataRow;
                        decimal amo = Convert.ToDecimal(datarows["FRECEIVEAMOUNTFOR_H"]);
                        int fid = Convert.ToInt32(datarows["fid"]);
                        decimal yglje = GetYglje(fid);
                        dic.Add(BillNo, yglje);
                    }
                }
                string sBillno = string.Join(",", dic.Select(s => s.Key).ToList());
                Entity entity = this.Model.BillBusinessInfo.GetEntity("F_POSW_Entity_ca9");
                var rowEntry = this.Model.GetEntityDataObject(entity, row);
                var yNo = rowEntry["F_POSW_Text_dvn"];
                if (yNo.IsNullOrEmptyOrWhiteSpace())
                {
                    this.View.Model.SetValue("F_POSW_Text_dvn", sBillno, row);
                    decimal kglje = dic.Select(s => s.Value).Sum(p => Convert.ToDecimal(p));
                    this.View.Model.SetValue("FActRecAmount", kglje, row);
                    this.View.Model.SetValue("F_POSW_Amount_j94", allAmount, row);
                }

                //this.View.Model.SetValue("F_POSW_CheckBox_xlc", 0, row);
            });
        }

        private decimal GetYglje(int fid)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT F_ZMN_SSYSKJE FROM T_AR_RECEIVEBILL WHERE FID={0} ", fid);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToDecimal(doc[0][0]);
            }
            return 0;
        }
    }
}
